<template>
    <div class="address_edit">
        <!-- 顶部提示信息，关联二手书主题 -->
        <div class="book-notice">
            <van-notice-bar left-icon="volume-o" scrollable>
                请确保收货地址准确，以便顺利收到您选购的二手书！
            </van-notice-bar>
        </div>
        <!-- 直接使用Vant地址编辑组件，具体用法参见官网 -->
        <van-address-edit :area-list="areaList" :address-info="addressInfo" show-postal show-delete show-set-default
            :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave" @delete="onDelete">
            <template #default>
                <div class="tips">
                    提醒：每次下单时会使用该地址，实际下单地址会根据您购物切换的地区进行智能判断，请在下单时确认。
                </div>
            </template>
        </van-address-edit>
    </div>
</template>

<script>
import { showToast } from 'vant';
import { areaList } from "@vant/area-data";
import { getAddressDetailByIdAPI, addAddressAPI, updateAddressAPI, deleteAddressByIdAPI } from "@/api/address.js";
export default {
    data() {
        return {
            id: parseInt(this.$route.query.id) || 0, //注意路由传参的方式
            areaList, //地区列表
            //addressInfo数据结构参见官网文档AddressEditInfo类型
            addressInfo: {
                //收货人信息初始值
                id: "", //每条地址的唯一标识
                name: "", //姓名
                tel: "", //电话
                province: "", //省份
                city: "", //城市
                county: "", //区县
                postalCode: "", //邮政编码s
                addressDetail: "", //详细地址
                isDefault: false, //是否选择默认
            },
        };
    },
    //生命周期调用
    created() {
        this.getAddressDetail();
    },
    methods: {
        //根据id获取地址数据
        getAddressDetail() {
            if (!this.id) {
                // id==0 则是新增，重置地址信息
                this.addressInfo = {
                    id: "",
                    name: "",
                    tel: "",
                    province: "",
                    city: "",
                    county: "",
                    postalCode: "",
                    addressDetail: "",
                    isDefault: false, // 新增地址默认不设为默认地址
                };
                return;
            }
            //调用接口，获取登录用户的收货地址
            getAddressDetailByIdAPI(this.id).then(result => {
                if (result.data) {
                    this.addressInfo.id = result.data.id;
                    this.addressInfo.name = result.data.name || "";
                    this.addressInfo.tel = result.data.tel || "";
                    this.addressInfo.province = result.data.province || "";
                    this.addressInfo.city = result.data.city || "";
                    this.addressInfo.county = result.data.county || "";
                    this.addressInfo.areaCode = result.data.area_code || "";
                    this.addressInfo.postalCode = result.data.postal_code || "";
                    this.addressInfo.addressDetail = result.data.addressDetail || result.data.address_detail || "";
                    this.addressInfo.isDefault = result.data.is_default == 1 ? true : false;
                }
            }).catch(() => {
                showToast("获取地址详情失败");
            });
        },

        // 处理保存地址
        onSave(content) {
            // 验证必填字段
            if (!content.name || !content.tel || !content.addressDetail) {
                showToast("请填写完整的地址信息");
                return;
            }
            
            // 准备参数
            let params = {
                name: content.name,
                tel: content.tel,
                province: content.province,
                city: content.city,
                county: content.county,
                area_code: content.areaCode,
                postal_code: content.postalCode || "",
                address_detail: content.addressDetail,
                is_default: content.isDefault ? 1 : 0 // 正确转换布尔值为 1/0
            };
            
            // 如果是编辑模式，需要传递 id
            if (this.id && content.id) {
                params.id = content.id;
            }
            
            // 根据是否有 id 判断是新增还是编辑
            const api = params.id ? updateAddressAPI : addAddressAPI;
            api(params).then(result => {
                const successMsg = result.msg || (params.id ? "地址更新成功" : "地址添加成功");
                if (content.isDefault) {
                    showToast(successMsg + "，已设置为默认地址");
                } else {
                    showToast(successMsg);
                }
                setTimeout(() => {
                    this.$router.go(-1); // 返回地址列表页
                }, 1000);
            }).catch((error) => {
                const errorMsg = error?.response?.data?.msg || error?.message || "保存地址失败，请重试";
                showToast(errorMsg);
            });
        },

        // 处理删除地址
        onDelete(content) {
            let id = content.id || this.id;
            if (!id) {
                showToast("地址ID不存在，无法删除");
                return;
            }
            //调用接口
            deleteAddressByIdAPI(id).then(result => {
                showToast(result.msg || "删除成功");
                setTimeout(() => {
                    this.$router.go(-1); //页面跳转
                }, 1000);
            }).catch((error) => {
                const errorMsg = error?.response?.data?.msg || error?.message || "删除地址失败，请重试";
                showToast(errorMsg);
            });
        },

    },
};
</script>

<style scoped lang="less">
@bgColor: #f9f5ed;
@mainColor: #8b4513;

.address_edit {
    min-height: 100vh;
    background: @bgColor;
		padding-top: 46px;

    // 顶部提示信息样式
    .book-notice {
        background-color: #f5e8d0;
        padding: 5px 10px;
        margin-bottom: 10px;
    }

    /deep/.van-address-edit {
        border-top: 5px solid @bgColor;
        position: relative;

        // 强化卡片主题与二手书籍的匹配程度
        .van-address-edit__input {
            border-left: 5px solid @mainColor; // 增加左侧边框，与主题色呼应
            margin-bottom: 20px; // 加大地址项之间的间距
            padding: 15px; // 增加内边距
            border-radius: 8px; // 添加圆角
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05); // 添加阴影
            background-color: white; // 为每个地址项添加白色背景
        }

        .van-address-edit__buttons {
            margin-top: 70px;

            // 修改保存和删除按钮样式
            .van-button {
                background-color: @mainColor;
                color: white;
                border: none;
                &:hover {
                    background-color: darken(@mainColor, 10%); // 鼠标悬停时颜色加深
                }
            }
        }

        .tips {
            padding: 12px 12px;
            font-size: 12px;
            color: @mainColor;
        }
    }
}
</style>